package com.huawei.aiosproj.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.util.TypedValue;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class StackedCardItemDecoration extends RecyclerView.ItemDecoration {

    private final int cardHeightPx;
    private final int peekHeightPx;
    private final int topCardMarginPx;
    public StackedCardItemDecoration(Context context, int cardHeightDp, int peekHeightDp, int topCardMarginDp) {
        Resources r = context.getResources();
        this.cardHeightPx = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                cardHeightDp,
                r.getDisplayMetrics()
        );
        this.peekHeightPx = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                peekHeightDp,
                r.getDisplayMetrics()
        );
        this.topCardMarginPx = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                topCardMarginDp,
                r.getDisplayMetrics()
        );
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int itemCount = state.getItemCount();

        if (position == 0) {
            // Apply top margin only to the first item
            outRect.top = topCardMarginPx;
        } else {
            // For subsequent items, make them overlap the previous one
            // The negative top margin creates the stacking effect.
            // Each card is pulled up by (cardHeight - peekHeight)
            outRect.top = -(cardHeightPx - peekHeightPx);
        }

        // Optional: Add left/right margins if you want spacing on the sides
        // int horizontalMarginPx = (int) TypedValue.applyDimension(
        //         TypedValue.COMPLEX_UNIT_DIP,
        //         16, // Example horizontal margin in dp
        //         parent.getContext().getResources().getDisplayMetrics()
        // );
        // outRect.left = horizontalMarginPx;
        // outRect.right = horizontalMarginPx;

        // Add bottom margin to the last item to ensure it's fully visible when scrolled to
        if (position == itemCount - 1) {
            outRect.bottom = peekHeightPx; // Or cardHeightPx if you want more space
        }
    }
    private int dpToPx(Context context, int dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density);
    }
}